package com.dingdang.controller;

import com.dingdang.data.Result;
import io.swagger.annotations.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/baiduMap")
@Api(value = "调用百度api")
public class BaiduMapController {


    final static String AK = "ANj3BEvRiL3bsPu1sUufxAToER9R3Ock";
    final static String ADDRESS_TO_LONGITUDEA_URL = "http://api.map.baidu.com/location/ip?coor=bd09ll";

    final static String LONGITUDE_TO_ADDRESS_URL = "http://api.map.baidu.com/reverse_geocoding/v3/?output=json&coordtype=BD09&pois=1";

    @GetMapping("/getMap")
    @ApiOperation(value = "获取当前地址的经纬度")
    public Result getMap() {
//        RestTemplate restTemplate = new RestTemplate();
        String url = ADDRESS_TO_LONGITUDEA_URL + "&ak=" + AK;
        HttpClient client = HttpClients.createDefault(); // 创建默认http连接
        HttpGet httpGet = new HttpGet(url);// 创建一个post请求
        String json= null;
        try {
            HttpResponse execute = client.execute(httpGet);
            json = EntityUtils.toString(execute.getEntity(), "utf-8");

            System.out.println(json);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.ok().setData(json);
    }
    /**
     * 逆地理编码
     * @param lat
     *        纬度 23.1067,
     * @param lng
     *        经度 113.325
     * @return
     */
    @GetMapping("/getMap2")
    @ApiOperation("获取具体位置")
    @ApiImplicitParams({
            @ApiImplicitParam(name ="lat",value = "纬度",paramType = "query",required = true),
            @ApiImplicitParam(name = "lng",value = "精度",paramType = "query",required = true)
    })
    public Result getMap2(@RequestParam("lat") float lat, @RequestParam("lng") float lng){
        String url = LONGITUDE_TO_ADDRESS_URL + "&ak=" + AK + "&location=" + lat + "," + lng;
//        log.info("请求url:" + url);
        HttpClient client = HttpClients.createDefault(); // 创建默认http连接
        HttpPost post = new HttpPost(url);// 创建一个post请求

        try {

            HttpResponse response = client.execute(post);// 用http连接去执行get请求并且获得http响应
            HttpEntity entity = response.getEntity();// 从response中取到响实体
            String html = EntityUtils.toString(entity);// 把响应实体转成文本
//            log.info("返回信息：" + html);
            // JSON转对象
            return Result.ok().setData(html);
        } catch (Exception e) {

//            log.error("逆地理编码[异常],", e);
            return null;
        }
    }



}
